import {
  WebSocketGateway,
  SubscribeMessage,
  MessageBody,
  WebSocketServer,
} from '@nestjs/websockets';
import {
  InsertMessageDto,
  CreateMessageDto,
} from '../../entity/message/dto/index';
import { MessageService } from '../message/message.service';
import { Server } from 'socket.io';

@WebSocketGateway(8889, {
  cors: {
    origin: '*',
  },
})
export class EventGateway {
  constructor(private messageService: MessageService) {}
  // 使用WebSocketServer装饰器获取Socket.IO服务器实例
  @WebSocketServer()
  server: Server;

  /**
   *
   * @param data 发送消息实体
   * @returns 返回成功消息实体
   */
  @SubscribeMessage('sendMessage')
  async handleMessage(@MessageBody() data: CreateMessageDto) {
    const message: InsertMessageDto = {
      creater: data.sendUser,
      createTime: new Date(),
      ...data,
    };
    const res = await this.messageService.insertMessage(message);
    console.log(res);

    const resData = {
      id: res.id,
      ...data,
    };
    this.server.emit('receiveMessage', resData);
    return '发送成功';
  }
}
